package com.yanftch.stopcoding.manager;

import com.intellij.concurrency.JobScheduler;
import com.intellij.openapi.application.ApplicationManager;
import com.yanftch.stopcoding.common.util.ExtJava;
import com.yanftch.stopcoding.common.util.LogUtil;
import com.yanftch.stopcoding.config.DefaultConfig;
import com.yanftch.stopcoding.storage.PluginState;
import com.yanftch.stopcoding.ui.StopCodingFrame;

import javax.swing.*;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class NotifyManager {
    private static final String TAG = "debug_NotifyManager";

    private static final ThreadLocal<ScheduledFuture> SCHEDULED_FUTURE_CONTEXT = new ThreadLocal<>();

    public static void init() {
        restart();
    }

    /**
     * 重新开启定时提醒任务
     */
    public static void restart() {
        stop();
        PluginState state = ApplicationManager.getApplication().getService(PluginState.class);
        boolean aSwitch = state.getSwitch();
        if (aSwitch) {
            ScheduledFuture scheduledFuture = JobScheduler.getScheduler().scheduleWithFixedDelay(new NotifyTaskRunnable(),
                    state.getMinute(), state.getMinute(), DefaultConfig.DEFAULT_PERIOD_UNIT);
            SCHEDULED_FUTURE_CONTEXT.set(scheduledFuture);
        }
        LogUtil.d(TAG, "重启定时任务...开关状态：" + aSwitch);
    }

    public static void stop() {
        LogUtil.d(TAG, "停止定时任务...");
        ScheduledFuture existScheduledFuture = SCHEDULED_FUTURE_CONTEXT.get();
        if (existScheduledFuture != null) {
            existScheduledFuture.cancel(true);
            SCHEDULED_FUTURE_CONTEXT.remove();
        }
    }


    /**
     * 通知处理
     */
    static class NotifyTaskRunnable implements Runnable {
        StopCodingFrame frame = null;

        @Override
        public void run() {
            PluginState state = ApplicationManager.getApplication().getService(PluginState.class);
            int minute = state.getMinute();
            String dialogTitle = state.getDialogTitle();
            String imageSrc = state.getImageSrc();
            String textSrc = state.getTextSrc();
            DefaultConfig.TextSourceEnum textSourceEnum = DefaultConfig.TextSourceEnum.fromString(textSrc);
            int type = textSourceEnum.index;
            if (frame == null) {
                frame = new StopCodingFrame(dialogTitle);
            }
            boolean showing = frame.isVisible();

            LogUtil.d(TAG, ExtJava.formatTime(System.currentTimeMillis()) + "  当前配置信息：" + minute + "分钟提醒一次，弹窗标题为：" + dialogTitle + "，图片源为：" + imageSrc + "，文案源为：" + textSrc + ", type：" + type + ", 当前是否正在显示：" + showing);
            SwingUtilities.invokeLater(() -> {
                if (showing) {
                    return;
                }
                frame.showPop(type, imageSrc);
            });
        }
    }
}
